package com.abapi.pay.admin.handler;

import com.abapi.cloud.common.utils.JsonUtil;
import com.abapi.cloud.socket.annotation.TcpEndpointHandler;
import com.abapi.cloud.socket.mapping.AbstractTcpEndpointHandler;
import com.abapi.cloud.socket.pojo.TcpSession;
import com.abapi.pay.admin.data.ClientData;
import com.abapi.pay.admin.data.ClientInfo;
import com.abapi.pay.admin.service.AbstractEndpointService;
import com.abapi.pay.core.biz.Decode;
import com.abapi.pay.core.dto.MessageDTO;
import io.netty.buffer.ByteBuf;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author ldx
 * @Date 2019/10/16 14:56
 * @Description
 * @Version 1.0.0
 */
@TcpEndpointHandler
@Component
public class AdminServiceTcpHandler extends AbstractTcpEndpointHandler {

    Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    HandlerEndpointFactory handlerEndpointFactory;

    static AdminServiceTcpHandler adminServiceTcpHandler;

    @PostConstruct
    public void init() {
        adminServiceTcpHandler = this;
        adminServiceTcpHandler.handlerEndpointFactory = this.handlerEndpointFactory;
    }

    private static String captureName(String s) {
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    @Override
    public void doOnOpen(TcpSession tcpSession) {
        logger.info("连接成功>>>>"+tcpSession.id().asLongText());
    }

    @Override
    public void doOnMessage(TcpSession tcpSession, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bs = new byte[buf.readableBytes()];
        buf.readBytes(bs);
        MessageDTO decode = Decode.decode(bs);
        logger.info("接受到消息"+JsonUtil.writeValueAsString(decode));
        AbstractEndpointService instance =adminServiceTcpHandler.handlerEndpointFactory.getInstance(captureName(HandlerEndpointContext.handlerClassMap.get(decode.getType()).getSimpleName()));
        instance.handler(tcpSession, decode);
    }

    @Override
    public void doOnError(TcpSession tcpSession, Throwable throwable) {
        logger.info("异常错误>>>>"+tcpSession.id());
        tcpSession.close();
    }

    @Override
    public void doOnClose(TcpSession tcpSession) {
        logger.info("连接关闭>>>>"+tcpSession.id().asLongText());
        cleanClient(tcpSession);
    }

    private void cleanClient(TcpSession tcpSession){
        ClientInfo clientInfo = ClientData.session.get(tcpSession.id().asLongText());
        ClientData.session.remove(tcpSession.id().asLongText());
        ClientData.clientData.remove(clientInfo.getProjectName());
        //List<ClientInfo> clientInfos = ClientData.clientData.get(clientInfo.getProjectName());
        //clientInfos.remove(clientInfo);
    }

    @Override
    public void doOnEvent(TcpSession tcpSession, Object evt) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state() == IdleState.READER_IDLE) {
            logger.error("READ超时 服务器主动断开连接:{}", tcpSession.id().asLongText());
            tcpSession.close();
        }else if (event.state() == IdleState.WRITER_IDLE) {
            logger.error("WRITER超时 服务器主动断开连接:{}", tcpSession.id().asLongText());
            tcpSession.close();
        }else if (event.state() == IdleState.ALL_IDLE) {
            logger.error("ALL超时 服务器主动断开连接:{}", tcpSession.id().asLongText());
            tcpSession.close();
        }
    }

}
